package com.sam.im.heiqun.uis.activities;

import android.content.Context;
import android.support.v7.app.AlertDialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.sam.im.heiqun.R;
import com.sam.im.heiqun.entities.UserEntivity;
import com.sam.im.heiqun.nets.PGService;
import com.sam.im.heiqun.utils.CashierInputFilter;
import com.sam.im.heiqun.utils.RequestRSAUtils;
import com.sam.im.heiqun.utils.ToolsUtils;
import com.yuyh.library.nets.callbacks.AbsAPICallback;
import com.yuyh.library.nets.exceptions.ApiException;
import com.yuyh.library.uis.activitys.BaseSwipeBackActivity;
import com.yuyh.library.utils.data.safe.MD5;
import com.yuyh.library.utils.toast.ToastUtils;
import com.yuyh.library.view.text.PasswordEditText;

import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.OnClick;

public class SendRedPackageGroupActivity extends BaseSwipeBackActivity implements TextWatcher {

    private static final String TAG = SendRedPackageGroupActivity.class.getSimpleName();
    @BindView(R.id.red_packet_count)
    EditText packageCount;
    @BindView(R.id.pre_v_back)
    ImageView preVBack;
    @BindView(R.id.edit_sendMoney)
    EditText sendMoney;
    @BindView(R.id.edit_message)
    EditText message;
    PasswordEditText payPSD;

    @BindView(R.id.money_count)
    TextView moneyCount;
    @BindView(R.id.explain_message)
    TextView explain;
    @BindView(R.id.change_type)
    TextView change;
    @BindView(R.id.sum_money)
    TextView moneyShow;

    @BindView(R.id.send)
    Button commit;

    @BindView(R.id.txt_pin)
    TextView pinImg;
    @BindView(R.id.tv_balance)
    TextView tvBalance ;
    private int sendType = 0;   // 0 拼运气    1 普通
    private AlertDialog payDialog;
    private Long groupId;
    PGService mPgService;
    private double balance;

    @Override
    public int getContentViewId() {
        return R.layout.activity_send_red_package_group;
    }

    @Override
    protected String getTitleText() {
        return getString(R.string.title_ordinary_red_packet);
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setWindowStatusBarColor(this, R.color.red9);
        sendMoney.addTextChangedListener(this);
        commit.setEnabled(false);
        groupId = getIntent().getLongExtra("destid", 0);
        mPgService = PGService.getInstance();
        mPgService.getBalance(ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<String>() {
            @Override
            protected void onResultError(ApiException ex) {
                showToast(getResources().getString(R.string.net_visit_exception));
            }

            @Override
            public void onNext(String s) {
                balance = Double.parseDouble(s);
                tvBalance.setText(getResources().getString(R.string.yu_e_1)+s+getResources().getString(R.string.yuan));
            }
        });
        InputFilter[] filters = {new CashierInputFilter()};//限定输入为金额模式
        sendMoney.setFilters(filters);
        packageCount.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                String money = sendMoney.getText().toString().trim();
                String trim = editable.toString().trim();
                if ("".equals(trim)||"".equals(money)||"0".equals(trim)|| Integer.parseInt(trim) > 100 ||0 == Double.parseDouble(money)||Double.parseDouble(money)>200) {
                    if (!"".equals(money)&&Double.parseDouble(money)>200){
                        commit.setText(getResources().getString(R.string.one_redpacket_out200));
                    }else {
                        commit.setText(getResources().getString(R.string.send_red_package));
                    }
                    if (Integer.parseInt(trim) > 100){
                        commit.setText(getResources().getString(R.string.one_num_100));
                    }
                    commit.setEnabled(false);
                    commit.setBackgroundResource(R.drawable.rp_bg_circle_btn);
                    moneyShow.setText("￥ 0.00");
                } else {
                    if (null == money || "".equals(money)) {
                        moneyShow.setText("￥ 0.00");
                        setunCanablesend();
                    } else {
                        if (0 == Double.parseDouble("".equals(trim)?"0": trim)) {
                            moneyShow.setText("￥ 0.00");
                            setunCanablesend();
                        } else {
                            if (Double.parseDouble(money)>balance){
                                commit.setText(getResources().getString(R.string.yue_nozu));
                                commit.setEnabled(false);
                                commit.setBackgroundResource(R.drawable.rp_bg_circle_btn);
                            }else {
                                commit.setText(getResources().getString(R.string.now_no));
                                commit.setEnabled(true);
                                commit.setBackgroundResource(R.drawable.rp_bg_circle_btn_y);
                                if (0 == sendType) {
                                    moneyShow.setText("￥ " + Double.parseDouble(money));
                                } else {
                                    moneyShow.setText("￥ " + (Double.parseDouble(trim) * Double.parseDouble(money)));
                                }
                            }

                        }
                    }
                }
            }
        });

    }

    @OnClick({R.id.change_type, R.id.send})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.send:
                doSend();

                break;
            case R.id.change_type:
                doChangeType();
                break;
            case R.id.pay_commit:
                String pwd = payPSD.getText().toString().trim();
                if ("".equals(pwd)) {
                    new ToastUtils().showLongToast(getResources().getString(R.string.please_import_pay_psd));
                } else {
                    validatePayPwd(pwd);
                }

                break;
            case R.id.pay_cancel:
                payDialog.dismiss();
                break;
            case R.id.pre_v_back:
                finish();
                break;
        }
    }

    /**
     * 做发送红包的逻辑操作
     */
    private void doSend() {

        final UserEntivity user = ToolsUtils.getUser();

        if (!ToolsUtils.currentNetState(this)) {
            return;
        }
        showProgress(null);
        String myUserId = ToolsUtils.getMyUserId();
        mPgService.getBalance(myUserId).subscribe(new AbsAPICallback<String>() {
            @Override
            protected void onResultError(ApiException ex) {
                Log.e(TAG, "onResultError: 发送群红包，接收用户余额出错");
                hideProgress();
            }

            @Override
            public void onNext(String s) {
                Float balance = Float.valueOf(s);
                hideProgress();
                Float money = Float.valueOf(sendMoney.getText().toString().trim());
                if (money > balance) {
                    showToast(getString(R.string.balance_lack_please_recharge));
                    startActivity(SelectRechargeTypeActivity.class);
                } else {
                    if (user.getPayInfo() == null || user.getPayInfo().equals("")) {
                        showToast(getString(R.string.please_set_pay_psd));
                        return;
                    }
                    showPayDialog();
                }
            }
        });
    }

    /**
     * 验证支付密码
     *
     * @param pwd
     */
    private void validatePayPwd(String pwd) {
        String payPsd = MD5.MD532(pwd);
        mPgService.validatePayPwd(payPsd, ToolsUtils.getMyUserId()).subscribe(new AbsAPICallback<String>() {
            @Override
            protected void onResultError(ApiException ex) {
//                    showToast("密码修改失败，请重试");
                new ToastUtils().showLongToast(getResources().getString(R.string.pay_psd_verify_defeat));
            }

            @Override
            public void onNext(String validateEntivity) {
                String money = sendMoney.getText().toString().trim();
                String liuyan = message.getText().toString().trim();
                String num = packageCount.getText().toString().trim();
                if (null == liuyan || "".equals(liuyan)) {
                    liuyan = getResources().getString(R.string.wish_you_good_fortune_and_every_success);
                }
                if (null == num || "".equals(num)) {
                    showToast(getResources().getString(R.string.please_import_correct_red_package_count));
                } else if (0 == Integer.parseInt(num)) {
                    showToast(getResources().getString(R.string.please_import_correct_red_package_count));
                } else {
                    sendRedPacket("" + groupId, money, liuyan, num);
                }
                payDialog.dismiss();
            }
        });
    }

    public void doChangeType() {
        sendType = sendType == 0 ? 1 : 0;
        if (sendType == 1) {
            moneyCount.setText(R.string.single_money);
            pinImg.setVisibility(View.GONE);
            explain.setText(getResources().getString(R.string.explain_red_packet_normal));
            change.setText(R.string.alter_to_spell_luck_red_package);
        } else {
            moneyCount.setText(R.string.total_money);
            pinImg.setVisibility(View.VISIBLE);
            explain.setText(getResources().getString(R.string.explain_red_packet_random));
            change.setText(R.string.alter_to_normal_red_package);
        }
    }

    private void showPayDialog() {
        View dialog = LayoutInflater.from(this).inflate(R.layout.transfer_account_dialog, null);
        payDialog = new AlertDialog.Builder(this).setView(dialog).create();
        payDialog.show();
        TextView payCancel = (TextView) dialog.findViewById(R.id.pay_cancel);
        TextView payCommit = (TextView) dialog.findViewById(R.id.pay_commit);
//        payPSD = ((EditText) dialog.findViewById(R.id.pay_psd));
        payPSD = ((PasswordEditText) dialog.findViewById(R.id.passwordInputView));
        payPSD.setSpacingWidth(0);
        popupKeyboard(payPSD);
        payCancel.setOnClickListener(this);
        payCommit.setOnClickListener(this);
    }

    private void popupKeyboard(final PasswordEditText editText) {

        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
                           public void run() {
                               InputMethodManager inputManager =
                                       (InputMethodManager) editText.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                               inputManager.showSoftInput(editText, 0);
                           }

                       },
                200);
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String packetCount = packageCount.getText().toString().trim();
        if ("".equals(s.toString())||0 == Double.parseDouble(s.toString())||Double.parseDouble(s.toString())>200||null == packetCount||"".equals(packetCount)||"0".equals(packetCount)) {
            commit.setEnabled(false);
            if (!"".equals(s.toString())&&Double.parseDouble(s.toString())>200){
                commit.setText(getResources().getString(R.string.one_redpacket_out200));
            }else {
                commit.setText(getResources().getString(R.string.now_no));
            }
            commit.setBackgroundResource(R.drawable.rp_bg_circle_btn);
            moneyShow.setText("￥ 0.00");
        } else {
            if (null == packetCount || "".equals(packetCount)) {
                moneyShow.setText("￥ 0.00");
                setunCanablesend();
            } else {
                if (0 == Double.parseDouble("".equals(s.toString().trim())?"0":s.toString().trim())) {
                    moneyShow.setText("￥ 0.00");
                    setunCanablesend();
                } else {
                    if (Double.parseDouble(s.toString())>balance){
                        commit.setText(getResources().getString(R.string.yue_nozu));
                        commit.setEnabled(false);
                        commit.setBackgroundResource(R.drawable.rp_bg_circle_btn);
                    }else {
                        commit.setText(getResources().getString(R.string.now_no));
                        commit.setEnabled(true);
                        commit.setBackgroundResource(R.drawable.rp_bg_circle_btn_y);
                        if (0 == sendType) {
                            moneyShow.setText("￥ " + Double.parseDouble(s.toString().trim()));
                        } else {
                            moneyShow.setText("￥ " + (Double.parseDouble(s.toString().trim()) * Double.parseDouble(packetCount)));
                        }
                    }


                }
            }
        }
    }

    private void setunCanablesend() {
        commit.setText(getResources().getString(R.string.now_no));
        commit.setEnabled(false);
        commit.setBackgroundResource(R.drawable.rp_bg_circle_btn);
    }

    @Override
    public void afterTextChanged(Editable s) {
    }

    /**
     * 发送红包
     *
     * @param uId
     * @param money
     * @param liuyan
     */
    public void sendRedPacket(final String uId, final String money, final String liuyan, final String num) {
        Log.e(TAG, "sendRedPacket:  群组红包---");

        String userId=ToolsUtils.getMyUserId();
        //要传给后台的参数全部封装成json，然后加密传给后台
        com.alibaba.fastjson.JSONObject json = new com.alibaba.fastjson.JSONObject();
        json.put("redPacketType", "2");
        json.put("userId", userId);
        json.put("redPacketCount", "1");
        json.put("redPacketContent", liuyan);
        json.put("destId", uId);
        json.put("destType", "2");
        json.put("redPacketAmount", money);
        json.put("command", "");
        json.put("limit", "");
        String content = RequestRSAUtils.setRsaContent(json);
        mPgService.sendRedPacket(content).subscribe(new AbsAPICallback<String>() {
        //mPgService.sendRedPacket(sendType == 0 ? "1" : "2", ToolsUtils.getMyUserId(), num, liuyan, uId, "2", money,"").subscribe(new AbsAPICallback<String>() {
            @Override
            protected void onResultError(ApiException ex) {
                new ToastUtils().showSingleToast(getResources().getString(R.string.send_faild));
            }

            @Override
            public void onNext(String data) {
                new ToastUtils().showSingleToast(getResources().getString(R.string.send_red_package_success));
              /*  Intent intent = new Intent();
                intent.putExtra("destid",uId);
                intent.putExtra("money",money);
                intent.putExtra("liuyan",liuyan);
                intent.putExtra("num",num);
                intent.putExtra("sendType",sendType==0?1:2);
                intent.putExtra("redPacketId",data);
                setResult(10,intent);*/
                finish();
            }
        });
    }

}
